<template>
  <div class="p-2 erpNativeList">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter="reload" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item name="contractTheme">
              <template #label><span title="合同主题">合同主题</span></template>
              <a-input placeholder="请输入合同主题" v-model:value="queryParam.contractTheme" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="contractCategory">
              <template #label><span title="合同类型">合同类型</span></template>
              <a-input placeholder="请输入合同类型" v-model:value="queryParam.contractCategory" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="productType">
              <template #label><span title="产品类型">产品类型</span></template>
              <a-input placeholder="请输入产品类型" v-model:value="queryParam.productType" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item name="contractSignName">
              <template #label><span title="签订人">签订人</span></template>
              <a-input placeholder="请输入签订人" v-model:value="queryParam.contractSignName" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="6">
              <a-form-item name="signDate">
                <template #label><span title="签订日期">签订日期</span></template>
                <a-range-picker value-format="YYYY-MM-DD" v-model:value="queryParam.signDate" class="query-group-cust" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="reload">查询</a-button>
                <a-button preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="content">
      <!--引用表格-->
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <!--插槽:table标题-->
        <template #tableTitle>
          <!-- 隐藏新增按钮 -->
          <!-- <a-button type="primary" v-auth="'contracts:contracts:add'" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button> -->
          <a-button type="primary" v-auth="'contracts:contracts:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button type="primary" v-auth="'contracts:contracts:importExcel'" preIcon="ant-design:import-outlined" @click="onImportXls"
            >导入</j-upload-button
          >
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="batchHandleDelete">
                  <Icon icon="ant-design:delete-outlined" />
                  删除
                </a-menu-item>
              </a-menu>
            </template>
            <a-button v-auth="'contracts:contracts:deleteBatch'"
              >批量操作
              <Icon icon="mdi:chevron-down" />
            </a-button>
          </a-dropdown>

          <!-- 高级查询 -->
          <super-query :config="superQueryConfig" @search="handleSuperQuery" />

          <!-- 文件操作按钮 -->
          <a-button
            type="primary"
            :disabled="selectedRowKeys.length !== 1"
            @click="handleUploadContractFile"
            preIcon="ant-design:upload-outlined"
            style="margin-left: 8px"
          >
            上传文件
          </a-button>
          <a-button
            type="primary"
            :disabled="selectedRowKeys.length !== 1"
            @click="handleViewContractFiles"
            preIcon="ant-design:file-text-outlined"
            style="margin-left: 8px"
          >
            查看合同文件
          </a-button>
          <a-button
            type="primary"
            :disabled="!canViewInvoiceFiles"
            @click="handleViewInvoiceFiles"
            preIcon="ant-design:file-search-outlined"
            style="margin-left: 8px"
          >
            查看发票文件
          </a-button>
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
        <!--字段回显插槽-->
        <template v-slot:bodyCell="{ column, record, index, text }"> </template>
      </BasicTable>
      <!--子表表格tab-->
      <a-tabs defaultActiveKey="1" style="margin: 10px">
        <a-tab-pane tab="合同金额信息" key="1">
          <ContractAmountInfoList />
        </a-tab-pane>
        <a-tab-pane tab="合同明细信息" key="2" forceRender>
          <ContractDetailInfoList />
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 表单区域 -->
    <ContractsModal ref="registerModal" @success="handleSuccess" @approve="handleApproveFromDetail" />
    <!-- 审批模态框 -->
    <ContractApproveModal ref="approveModal" @success="handleApproveSuccess" />
    <!-- 文件上传模态框 -->
    <a-modal v-model:visible="uploadModalVisible" title="上传合同文件" :width="600" :footer="null">
      <div class="file-upload-container">
        <a-upload-dragger
          v-model:fileList="fileUploadList"
          :multiple="false"
          :showUploadList="{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: true,
          }"
          name="file"
          :headers="{ 'X-Access-Token': userStore.getToken }"
          :before-upload="handleBeforeUploadFile"
          :customRequest="customUploadFile"
        >
          <p class="ant-upload-drag-icon">
            <Icon icon="ant-design:cloud-upload-outlined" style="font-size: 40px; color: #40a9ff" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
          <p class="ant-upload-hint">支持单文件上传，文件大小不超过10M</p>
        </a-upload-dragger>

        <div class="file-upload-actions">
          <a-button @click="uploadModalVisible = false">关闭</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 查看合同文件模态框 -->
    <a-modal v-model:visible="viewFilesModalVisible" title="合同文件列表" :width="800" :footer="null">
      <div class="files-container">
        <div class="files-header">
          <h4>当前合同: {{ currentRecord?.contractTheme || '未知合同' }}</h4>
          <a-button type="primary" @click="addFileModalVisible = true" preIcon="ant-design:plus-outlined">
            添加文件
          </a-button>
        </div>

        <div class="files-list" v-if="filesList.length > 0">
          <a-list :data-source="filesList" :bordered="false">
            <template #renderItem="{ item }">
              <a-list-item>
                <div class="file-item">
                  <div class="file-info">
                    <Icon icon="ant-design:file-outlined" style="margin-right: 8px; color: #1890ff;" />
                    <span class="file-name">{{ item.fileName || item.name }}</span>
                    <span class="file-size">{{ formatFileSize(item.fileSize) }}</span>
                  </div>
                  <div class="file-actions">
                    <a-button type="link" size="small" @click="handlePreviewFile(item)">
                      预览
                    </a-button>
                    <a-button type="link" size="small" @click="handleDownloadFile(item)">
                      下载
                    </a-button>
                    <a-button type="link" size="small" danger @click="handleDeleteFile(item)">
                      删除
                    </a-button>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>

        <div v-else class="no-files">
          <a-empty description="暂无文件" />
        </div>
      </div>
    </a-modal>

    <!-- 添加文件模态框 -->
    <a-modal v-model:visible="addFileModalVisible" title="添加合同文件" :width="500" :footer="null">
      <div class="add-file-container">
        <a-upload-dragger
          :multiple="false"
          :showUploadList="false"
          name="file"
          :headers="{ 'X-Access-Token': userStore.getToken }"
          :before-upload="handleBeforeUploadFile"
          :customRequest="customAddFile"
        >
          <p class="ant-upload-drag-icon">
            <Icon icon="ant-design:cloud-upload-outlined" style="font-size: 40px; color: #40a9ff" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
          <p class="ant-upload-hint">支持单文件上传，文件大小不超过10M</p>
        </a-upload-dragger>

        <div class="add-file-actions">
          <a-button @click="addFileModalVisible = false">取消</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 查看发票文件模态框 -->
    <a-modal
      v-model:visible="viewInvoiceFilesModalVisible"
      title="查看发票文件"
      :width="800"
      :footer="null"
    >
      <div class="invoice-files-container">
        <!-- 申请发票按钮 -->
        <div class="invoice-actions" style="margin-bottom: 16px;">
          <a-button
            type="primary"
            @click="handleApplyForInvoiceInModal"
            preIcon="ant-design:file-add-outlined"
            :disabled="invoiceFilesList.length > 0"
          >
            申请发票
          </a-button>
          <span v-if="invoiceFilesList.length > 0" style="margin-left: 8px; color: #999; font-size: 12px;">
            已有发票文件，无需重复申请
          </span>
        </div>

        <div v-if="invoiceFilesList.length > 0" class="files-list">
          <a-list :data-source="invoiceFilesList" item-layout="horizontal">
            <template #renderItem="{ item }">
              <a-list-item>
                <div class="file-item">
                  <div class="file-info">
                    <div class="file-name">
                      <Icon icon="ant-design:file-text-outlined" style="margin-right: 8px; color: #1890ff" />
                      {{ item.fileName || item.name || '未命名文件' }}
                    </div>
                    <div class="file-meta">
                      <span class="file-size">{{ formatFileSize(item.fileSize || item.size) }}</span>
                      <span class="file-time" v-if="item.createTime">
                        上传时间：{{ item.createTime }}
                      </span>
                    </div>
                  </div>
                  <div class="file-actions">
                    <a-button
                      type="link"
                      size="small"
                      @click="handlePreviewInvoiceFile(item)"
                    >
                      预览
                    </a-button>
                        <a-button
                      type="link"
                      size="small"
                      @click="handleDownloadInvoiceFile(item)"
                    >
                      下载
                    </a-button>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>

        <div v-else class="no-files">
          <a-empty description="暂无发票文件" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" name="contracts-contracts" setup>
  import { ref, reactive, computed, unref, provide, onMounted, onBeforeUnmount } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import ContractsModal from './components/ContractsModal.vue';
  import ContractApproveModal from './components/ContractApproveModal.vue';
  import { columns, superQuerySchema } from './Contracts.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, saveOrUpdate, getContractFiles, deleteContractFile, applyForInvoice, getInvoiceFiles } from './Contracts.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import ContractAmountInfoList from './ContractAmountInfoList.vue';
  import ContractDetailInfoList from './ContractDetailInfoList.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { cloneDeep } from 'lodash-es';
  
  import axios from 'axios';
  import { message } from 'ant-design-vue';
  const formRef = ref();
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const registerModal = ref();
  const approveModal = ref();
  const userStore = useUserStore();
  
  // 文件上传相关状态
  const uploadModalVisible = ref(false);
  const currentUploadRecord = ref(null);
  const fileUploadList = ref([]);

  // 查看合同文件相关状态
  const viewFilesModalVisible = ref(false);
  const addFileModalVisible = ref(false);
  const currentRecord = ref(null);
  const filesList = ref([]);

  // 查看发票文件相关状态
  const viewInvoiceFilesModalVisible = ref(false);
  const invoiceFilesList = ref([]);
  //注册table数据
  const { tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '合同模块',
      api: list,
      columns,
      canResize: false,
      useSearchForm: false,
      clickToRowSelect: true,
      rowSelection: { type: 'checkbox' }, // Change to checkbox for multi-selection and "Select All"
      actionColumn: {
        width: 180,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        let rangerQuery = await setRangeQuery();
        return Object.assign(params, rangerQuery);
      },
      pagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20'],
      },
    },
    exportConfig: {
      name: '合同模块',
      url: getExportUrl,
      params: setRangeQuery,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const mainId = computed(() => (unref(selectedRowKeys).length > 0 ? unref(selectedRowKeys)[0] : ''));
  //下发 mainId,子组件接收
  provide('mainId', mainId);

  // 计算是否可以查看发票文件
  const canViewInvoiceFiles = computed(() => {
    return selectedRowKeys.value.length === 1; // 只要选中一条记录即可
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 重置查询条件
   */
  function searchReset() {
    Object.keys(queryParam).forEach(key => delete queryParam[key]);
    reload();
  }

  /**
   * 处理高级查询
   */
  function handleSuperQuery(params) {
    Object.assign(queryParam, params);
    reload();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.edit(record);
  }

  /**
   * 详情事件
   */
  function handleDetail(record: Recordable) {
    registerModal.value.detail(record);
  }



  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    selectedRowKeys.value = [];
     reload();
  }

  /**
   * 审批成功回调
   */
  function handleApproveSuccess(result?: any) {
    (selectedRowKeys.value = []) && reload();

  }

  /**
   * 从详情模态框处理审批
   */
  function handleApproveFromDetail(record: Recordable) {
    console.log('handleApproveFromDetail called with record:', record);
    // 关闭详情模态框
    registerModal.value.handleCancel();
    // 打开审批模态框
    console.log('Opening approve modal...');
    approveModal.value.open(record);
  }

  /**
   * 处理上传合同文件
   */
  function handleUploadContractFile() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请先选中一条合同记录');
      return;
    }
    const record = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    currentUploadRecord.value = record;
    uploadModalVisible.value = true;
  }

  /**
   * 处理查看合同文件
   */
  async function handleViewContractFiles() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请先选中一条合同记录');
      return;
    }
    const record = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    currentRecord.value = record;
    await loadFilesList();
    viewFilesModalVisible.value = true;
  }

  /**
   * 处理申请发票
   */
  async function handleApplyForInvoice() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请先选中一条合同记录');
      return;
    }

    try {
      // 获取选中的记录数据
      const record = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
      if (!record) {
        return;
      }

      console.log('申请发票的合同数据:', record);

      // 调用申请发票接口，传入所选行的所有数据
      const response = await applyForInvoice(record);

      if (response.success) {
        message.success('已提交发票申请');
        // 刷新列表
        reload();
      } else {
        message.error(response.message || '申请发票失败');
      }
    } catch (error) {
      message.error('申请发票失败');
    }
  }

  /**
   * 加载文件列表
   */
  async function loadFilesList() {
    try {
      if (!currentRecord.value?.id) return;

      const response = await getContractFiles(currentRecord.value.id);
      if (response.success) {
        filesList.value = response.result || [];
      } else {
        filesList.value = [];
        message.error(response.message || '获取文件列表失败');
      }
    } catch (error) {
      console.error('获取文件列表失败:', error);
      filesList.value = [];
      message.error('获取文件列表失败');
    }
  }

  /**
   * 处理查看发票文件
   */
  async function handleViewInvoiceFiles() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请先选中一条合同记录');
      return;
    }

    const record = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    if (!record) {
      message.error('未找到选中的合同记录');
      return;
    }

    try {
      await loadInvoiceFilesList(record.id);
      viewInvoiceFilesModalVisible.value = true;
    } catch (error) {
      console.error('查看发票文件失败:', error);
      message.error('查看发票文件失败');
    }
  }

  /**
   * 加载发票文件列表
   */
  async function loadInvoiceFilesList(contractId) {
    try {
      const response = await getInvoiceFiles(contractId);
      invoiceFilesList.value = response;
      console.log('发票文件列表:', invoiceFilesList.value);
    } catch (error) {
      console.error('获取发票文件列表失败:', error);
      invoiceFilesList.value = [];
      message.error('获取发票文件列表失败');
    }
  }

  /**
   * 预览发票文件
   */
  async function handlePreviewInvoiceFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('文件ID缺失，无法预览');
        return;
      }

      // 获取文件预览URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/contracts/contracts/previewFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 打开预览窗口
      window.open(url, '_blank');

      console.log('发票文件预览请求已发送:', url);
    } catch (error) {
      console.error('预览发票文件失败:', error);
      message.error('预览发票文件失败');
    }
  }

  /**
   * 下载发票文件
   */
  async function handleDownloadInvoiceFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('文件ID缺失，无法下载');
        return;
      }

      // 获取文件下载URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/FinancialInvoice/financialInvoice/downloadFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 创建下载链接
      const a = document.createElement('a');
      a.href = url;
      a.download = file.fileName || file.name || '发票文件';
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      console.log('发票文件下载请求已发送:', url);
    } catch (error) {
      console.error('下载发票文件失败:', error);
      message.error('下载发票文件失败');
    }
  }

  
  /**
   * 在弹窗中处理申请发票
   */
  async function handleApplyForInvoiceInModal() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请先选中一条合同记录');
      return;
    }

    try {
      // 获取选中的记录数据
      const record = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
      if (!record) {
        message.error('未找到选中的合同记录');
        return;
      }

      console.log('申请发票的合同数据:', record);

      // 调用申请发票接口，传入所选行的所有数据
      const response = await applyForInvoice(record);

      if (response.success) {
        message.success('已提交发票申请');
        // 刷新发票文件列表
        await loadInvoiceFilesList(record.id);
        // 刷新主列表
        reload();
      } else {
        message.error(response.message || '申请发票失败');
      }
    } catch (error) {
      console.error('申请发票失败:', error);
      message.error('申请发票失败');
    }
  }

  /**
   * 格式化文件大小
   */
  function formatFileSize(size) {
    if (!size) return '未知大小';
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;
    while (size >= 1024 && index < units.length - 1) {
      size /= 1024;
      index++;
    }
    return `${size.toFixed(1)} ${units[index]}`;
  }

  /**
   * 文件上传成功回调
   */
  async function handleFileUploaded(file, response) {
    try {
      if (currentUploadRecord.value) {
        // 更新当前记录的合同文件字段为"已上传"
        const updateData = {
          ...currentUploadRecord.value,
          contractFile: '已上传'
        };

        // 调用编辑接口更新数据库
        const updateResponse = await saveOrUpdate(updateData, true);

        if (updateResponse.success) {
          message.success('文件上传成功');
          uploadModalVisible.value = false;
          reload(); // 刷新表格数据
        } else {
          message.error(updateResponse.message || '更新合同记录失败');
        }
      } else {
        message.success('文件上传成功');
        uploadModalVisible.value = false;
        reload(); // 刷新表格数据
      }
    } catch (error) {
      console.error('更新合同记录失败:', error);
      message.error('文件上传成功，但更新合同记录失败');
    }
  }

  /**
   * 预览文件
   */
  async function handlePreviewFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('文件ID缺失，无法预览');
        return;
      }

      // 获取文件预览URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/contracts/contracts/previewFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 打开预览窗口
      window.open(url, '_blank');

      console.log('文件预览请求已发送:', url);
    } catch (error) {
      console.error('预览文件失败:', error);
      message.error('预览文件失败');
    }
  }

  /**
   * 下载文件
   */
  async function handleDownloadFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('文件ID缺失，无法下载');
        return;
      }

      // 获取文件下载URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/contracts/contracts/downloadFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 创建下载链接
      const a = document.createElement('a');
      a.href = url;
      a.download = file.fileName || file.name || '文件';
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      console.log('文件下载请求已发送:', url);
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败');
    }
  }

  /**
   * 删除文件
   */
  async function handleDeleteFile(file) {
    try {
      const response = await deleteContractFile(file.id);
      if (response.success) {
        message.success('删除文件成功');
        await loadFilesList(); // 重新加载文件列表
      } else {
        message.error(response.message || '删除文件失败');
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      message.error('删除文件失败');
    }
  }

  /**
   * 自定义文件上传
   */
  const customUploadFile = async ({ file, onProgress, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('contractId', currentUploadRecord.value.id);

      const response = await axios.post('/jeecg-boot/contracts/contracts/uploadFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-Access-Token': userStore.getToken,
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        },
      });

      if (response.data.success) {
        onSuccess(response.data, file);
        // 调用新的上传成功回调，传入响应数据
        await handleFileUploaded(file, response);
      } else {
        onError(new Error(response.data.message || '上传失败'));
        message.error(response.data.message || '上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
       message.error('文件上传失败');
    }
  };

  /**
   * 自定义添加文件上传
   */
  const customAddFile = async ({ file, onProgress, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('contractId', currentRecord.value.id);

      const response = await axios.post('/jeecg-boot/contracts/contracts/uploadFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-Access-Token': userStore.getToken,
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        },
      });

      if (response.data.success) {
        onSuccess(response.data, file);

        // 上传成功后，更新合同文件状态
        try {
          const updateData = {
            ...currentRecord.value,
            contractFile: '已上传'
          };

          const updateResponse = await saveOrUpdate(updateData, true);

          if (updateResponse.success) {
            message.success('文件上传成功');
            reload(); // 刷新表格数据
          } else {
            message.error(updateResponse.message || '更新合同状态失败');
          }
        } catch (updateError) {
          console.error('更新合同状态失败:', updateError);
          message.error('文件上传成功，但更新合同状态失败');
        }

        addFileModalVisible.value = false;
        await loadFilesList(); // 重新加载文件列表
      } else {
        onError(new Error(response.data.message || '上传失败'));
        message.error(response.data.message || '上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
      message.error('文件上传失败');
    }
  };

  /**
   * 文件上传前检查
   */
  const handleBeforeUploadFile = (file) => {
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('文件大小不能超过10MB');
      return false;
    }
    return true;
  };

  // 监听表格审批按钮点击事件
  onMounted(() => {
    window.addEventListener('contract-approve-click', handleApproveFromTable);
  });
  onBeforeUnmount(() => {
    window.removeEventListener('contract-approve-click', handleApproveFromTable);
  });

  function handleApproveFromTable(e) {
    const record = e.detail;
    approveModal.value.open(record);
  }


  /**
   * 操作栏
   */
  function getTableAction(record) {
    const actions = [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'contracts:contracts:edit',
      },
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'contracts:contracts:delete',
      },
    ];

    return actions;
  }

  /* ----------------------以下为原生查询需要添加的-------------------------- */
  const toggleSearchStatus = ref<boolean>(false);
  const labelCol = reactive({
    xs: 24,
    sm: 4,
    xl: 6,
    xxl: 4,
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });


  let rangeField = 'signDate,';

  /**
   * 设置范围查询条件
   */
  async function setRangeQuery() {
    let queryParamClone = cloneDeep(queryParam);
    if (rangeField) {
      let fieldsValue = rangeField.split(',');
      fieldsValue.forEach((item) => {
        if (queryParamClone[item]) {
          let range = queryParamClone[item];
          queryParamClone[item + '_begin'] = range[0];
          queryParamClone[item + '_end'] = range[1];
          delete queryParamClone[item];
        } else {
          queryParamClone[item + '_begin'] = '';
          queryParamClone[item + '_end'] = '';
        }
      });
    }
    return queryParamClone;
  }
</script>
<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust {
      min-width: 100px !important;
    }
    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }
    .ant-form-item:not(.ant-form-item-with-help) {
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),
    :deep(.ant-input-number) {
      width: 100%;
    }
  }
  .erpNativeList {
    height: 100%;
    .content {
      background-color: #fff;
      height: 100%;
    }
  }
  
  .file-upload-container {
    padding: 20px;
  }

  .file-upload-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  .files-container {
    padding: 20px;
  }

  .files-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
  }

  .files-header h4 {
    margin: 0;
    color: #333;
  }

  .files-list {
    max-height: 400px;
    overflow-y: auto;
  }

  .file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
  }

  .file-info {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .file-name {
    margin-right: 10px;
    font-weight: 500;
  }

  .file-size {
    color: #999;
    font-size: 12px;
  }

  .file-actions {
    display: flex;
    gap: 8px;
  }

  .no-files {
    text-align: center;
    padding: 40px 0;
  }

  .add-file-container {
    padding: 20px;
  }

  .add-file-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }
</style>
